import {InfoCircleOutlined} from '@ant-design/icons'
import {Button, Card, DatePicker, Input, Form, Upload, Radio, Select, message, Modal} from 'antd'
import {connect, history} from 'umi'
import React, {useEffect, useState} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import {getEmployeeById, sendMail, getQRCode, getEncryptId} from './service'
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import {isOfferList, laborContractYearsList} from '@/utils/constant'


const FormItem = Form.Item
const {Option} = Select


const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 7,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: {
      span: 10,
    },
  },
}
const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 10,
      offset: 7,
    },
  },
}

const Email = (props) => {
  const {submitting, match, currentUser, dispatch} = props
  const [form] = Form.useForm()
  const [showPublicUsers, setShowPublicUsers] = React.useState(false)
  const [employee, setEmployee] = React.useState({})
  const [qrCodeUrl, setQrCodeUrl] = React.useState('')
  const [saveInfoUrl, setSaveInfoUrl] = React.useState('')
  const [dialogVisible, setDialogVisible] = React.useState(false)
  const {employeeId} = match.params
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [hireFileList, setHireFileList] = useState([]);
  const [entryFileList, setEntryFileList] = useState([]);

  const fileProps =(type) => ({
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    fileList: type ? (type==='hire' ? hireFileList : entryFileList) : fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, info.file.response]);
          message.success(`${info.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
      let files = info.fileList.filter(item => item.status);

      if (type){
        type === 'hire' ? setHireFileList(files) : setEntryFileList(files);
      }else {
        setFileList(files);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  });

  useEffect(() => {
    getEmployeeById(employeeId).then((res) => {
      setEmployee(res)
    });
    /*getQRCode(`http://hr.zhangtai.com.cn/h5/#/pages/portal/index?oid=${employeeId}`).then((data) => {
      setQrCodeUrl(data)
    })*/
    getEncryptId(employeeId).then(res => {
      if (res) {
        getQRCode(`https://hr.zhangtai.com.cn/h5/#/pages/portal/index?oid=${encodeURIComponent(res)}`).then((data) => {
          setQrCodeUrl(data)
        });
        setSaveInfoUrl(`https://hr.zhangtai.com.cn/admin/#/invitation?oid=${encodeURIComponent(res)}`)
      }
    })

  }, []);

  const formatTemplate = (employee) => {
    return '<div><strong>' + employee.name + ', 您好：</strong></div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;当您收到这封邮件的时候，您将揭开人生新的篇章！</div>' +
      `<div>&nbsp;&nbsp;&nbsp;&nbsp;通过公司面试评估，公司决定聘用您为 ${employee.orgname} ${employee.unitname} ${employee.jobname} 一职。</div>` +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;“城市因我们而美好，生活因我们而幸福”的企业使命使每个彰泰人充满职业自豪感，“信任、尊重、合作、分享，持续为客户创造价值”的企业文化价值观将为每个彰泰人提供一个没有天花板的舞台，这一切使每个职业人心之向往。</div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;欢迎加入彰泰，成为彰泰的一员，相信这将是一个崭新的开始！</div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;期望您的入职日期为 ' + moment(employee.hiredate).format('YYYY-MM-DD') + ' 前。公司将与您签订 ' + laborContractYearsList.find(e => e.value === employee.laborContractYears)?.label + ' 的劳动合同，自入职当天开始，试用期 ' +
      employee.probationday + ' 个月【非中层干部员工（即M7/P8以下职级的员工）视工作表现和经领导批准后可提前3-5个月发起转正申请】。希望您与公司共同发展并祝您工作愉快！</div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;<strong>您的薪资福利、报到手续、入职前需提前准备物料等，详细见附件“录用邀约函”。</strong></div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;本录用邀约函自本封邮件首次进入您指定的收件系统之日起，有效期限为三个工作日，若您愿意接受“录用邀约函”信息及条款，请您在“员工信息采集”填写个人基本信息及上传您本人签字确认“录用邀约函”回执部分以示确认，超过三个工作日本录用邀约函将自动失效；您逾期未报到，本录用邀约函自动失效。</div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;如您需要帮助，请及时与我们联系，招聘对接人' + currentUser.name + '；联系电话 ' + currentUser.mobile + '</div>' +
      '<div>&nbsp;&nbsp;&nbsp;&nbsp;<strong>我们热切期待您的加入！请扫描以下二维码或点击链接（<a target="_blank" href="' + saveInfoUrl + '">点击填写个人信息</a>）进行个人信息填报。</strong></div>' +
      '<img src="data:image/png;base64,' + qrCodeUrl + '"/>' +
      `<div style="text-align: right">${employee.employerCompany}</div>` +
      '<div style="text-align: right">' + moment().format('YYYY 年 MM 月 DD 日') + '</div>'
  };

  const onFinish = ({template, privatemail, ...values}) => {
    setLoading(true);
    if (dispatch) {
      dispatch({
        type: 'recruitmentAndEmail/sendMail',
        payload: {
          ...values,
          oid: employee.oid,
          receive: employee.privatemail,
          content: formatTemplate(employee),
          url: fileUploadUrls
        }
      }).then(() => {
        getEmployeeById(employeeId).then((res) => {
          setEmployee(res);
        });
        message.success('发送成功');
        history.push(`/recruitment/offer`);
      }).finally(() => {
        setLoading(false);
        setFileUploadUrls([]);
      });
    }
  };

  const onValuesChange = (changedValues) => {
    const {publicType} = changedValues
    if (publicType) setShowPublicUsers(publicType === '2')
  }

  const onPreviewEmail = () => {
    setDialogVisible(true)
  }

  const handleDialogClose = () => {
    setFileUploadUrls([]);
    setDialogVisible(false)
  }

  return (
    <PageHeaderWrapper title='offer邮件发送' content=''>
      <Card bordered={false}>
        <Form
          hideRequiredMark
          style={{
            marginTop: 8,
          }}
          form={form}
          name="basic"
          initialValues={{
            template: 0,
            subject: '入职Offer',
          }}
          onFinish={onFinish}
          onValuesChange={onValuesChange}
        >
          <FormItem
            {...formItemLayout}
            label="邮件标题"
            name="subject"
            rules={[
              {
                required: true,
                message: '请输入邮件标题',
              },
            ]}
          >
            <Input placeholder="请输入邮件标题"/>
          </FormItem>
          <FormItem {...formItemLayout} label="收件人">
            <div>{employee.name}</div>
          </FormItem>
          <FormItem {...formItemLayout} label="邮箱地址">
            <div>{employee.privatemail}</div>
          </FormItem>
          <FormItem {...formItemLayout} label="是否发送过Offer邮件">
            <div>{isOfferList[employee.isOffer]?.label}</div>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="邮件模版"
            name="template"
            rules={[
              {
                required: true,
                message: '请选择邮件模版',
              },
            ]}
          >
            <Select placeholder="请选择">
              {['默认模版'].map((item, index) => {
                return (
                  <Option value={index} key={index}>
                    {item}
                  </Option>
                )
              })}
            </Select>
          </FormItem>
          <FormItem {...formItemLayout} name='entry' label="入职须知" extra='入职须知必传'
                    rules={[{required: true, message: '入职须知不能为空'}]}>
            <Upload {...fileProps('entry')}>
              <Button>
                <UploadOutlined/> 点击上传附件
              </Button>
            </Upload>
          </FormItem>
          <FormItem {...formItemLayout} name='hire' label="录用邀约函" extra='录用邀约函必传'
                    rules={[{required: true, message: '录用邀约函不能为空'}]}>
            <Upload {...fileProps('hire')}>
              <Button>
                <UploadOutlined/> 点击上传附件
              </Button>
            </Upload>
          </FormItem>
          <FormItem {...formItemLayout} label="岗位薪资测算表">
            <Upload {...fileProps('')}>
              <Button>
                <UploadOutlined/> 点击上传附件
              </Button>
            </Upload>
          </FormItem>
          <FormItem {...submitFormLayout} style={{marginTop: 32}}>
            <Button type="primary" htmlType="submit" disabled={!employee.privatemail} loading={loading}
                    style={{marginRight: 32}}>
              发送邮件
            </Button>
            <Button onClick={onPreviewEmail}>
              预览
            </Button>
          </FormItem>
        </Form>
        <Modal
          okText="确定"
          cancelText="返回"
          title="邮件预览"
          width='800px'
          visible={dialogVisible}
          onOk={handleDialogClose}
          onCancel={handleDialogClose}
        >
          <div dangerouslySetInnerHTML={{__html: formatTemplate(employee)}}/>
        </Modal>

      </Card>
    </PageHeaderWrapper>
  )
}

export default connect(({user, loading}) => ({
  currentUser: user.currentUser,
  submitting: loading.effects['recruitmentAndEmail/sendMail'],
}))(Email)
